//
//  FCAddRelationGroupSubViewController.m
//  customerRelation
//
//  Created by 陈文斌 on 2019/6/12.
//

#import "FCAddRelationGroupSubViewController.h"
#import "CustomerRelationHeader.h"
#import "UIViewController+runtimeCheck.h"
#import "UIViewController+returnBlock.h"
#import "FCCustomerRelationRequest.h"
#import "FCRelationTypeManagerChoiceViewController.h"
#import "UIViewController+returnBlock.h"

@interface FCAddRelationGroupSubViewController ()
<
settinngViewControllDelegate,
UITableViewDelegate
>
@property (nonatomic, strong) NSMutableArray<FCEmployeeModel *> *employeeArr;

@end

#define RelationTypeName customerRelationLocaChanged(@"分组名称", @"分组名称")
#define EmployeeName customerRelationLocaChanged(@"授权负责人", @"授权负责人")
@implementation FCAddRelationGroupSubViewController
- (NSMutableArray<FCEmployeeModel *> *)employeeArr{
    if (!_employeeArr) {
        _employeeArr = [NSMutableArray array];
    }
    return _employeeArr;
}

- (void)setupContentUI {
    self.settingDelegate = self;
    self.tableView.delegate = self;
    
    tableObj *relationTypeName = [tableObj itemWithTitle:RelationTypeName value:self.relationType.name placeHolder:customerRelationLocaChanged(@"global_general_input_notice", @"请输入")  cellType:FCTableCellInput];
    relationTypeName.choice = YES;
    
    [relationTypeName addObserver:self forKeyPath:@"value" options:NSKeyValueObservingOptionNew context:nil];
    
    tableObj *employeeName = [tableObj itemWithTitle:EmployeeName value:self.relationType.manager.Name placeHolder:customerRelationLocaChanged(@"global_general_choose_please", @"请选择") cellType:FCTableCellChoice];
//    [employeeName addObserver:self forKeyPath:@"value" options:NSKeyValueObservingOptionNew context:nil];
    
    self.contentArr = [NSMutableArray arrayWithObjects:@[relationTypeName, employeeName], nil];
    if (self.relationType.banModify) {
        self.isCloseEdit = YES;
    }
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    BOOL isEnabled = YES;
    tableObj *relationTypeName = [self getReturnCellWithCellName:RelationTypeName];
    if (relationTypeName.value.length == 0) {
        isEnabled = NO;
    }
//    for (NSArray *arr in self.contentArr) {
//        for (tableObj *obj in arr) {
//            if (!(obj.value.length > 0)) {
//                isEnabled = NO;
//            }
//        }
//    }
    self.buttonStateBlock(isEnabled);
}

- (void)dealloc {
    tableObj *relationTypeName = [self getReturnCellWithCellName:RelationTypeName];
    [relationTypeName removeObserver:self forKeyPath:@"value"];
//    for (NSArray *arr in self.contentArr) {
//        for (tableObj *obj in arr) {
//            [obj removeObserver:self forKeyPath:@"value"];
//        }
//    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupContentUI];
}

#pragma mark - delegate
-(UITableViewCell*)getOthertableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    return nil;
}

-(void)getComontableView:(UITableView *)tableView andTableViewCell:(UITableViewCell*)cell cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    cell.selectionStyle = UIAccessibilityTraitNone;
}

// 键盘将弹起
- (void)keyboardWillShowWithNotification:(NSNotification *)notification cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

// 键盘将关闭
- (void)keyboardWillHideWithNotification:(NSNotification *)notification cellForRowAtIndexPath:(NSIndexPath *)indexPath andkeyBorardTool:(id)keyBorardTool {
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([self getReturnCellIndexWithCellName:EmployeeName] == indexPath) {
//        UIViewController *con = [self pushAppControllerWithControllerName:@"FCChoiceEmployeeListViewController" andObjectData:@{@"choicedArr":self.employeeArr, @"maxCount": @(1)} andTitle:EmployeeName];
        WJCWeakSelf
//        con.idBlock = ^(NSArray<FCEmployeeModel *> *employees) {
//            weakSelf.employeeArr = [NSMutableArray arrayWithArray:employees];
//            NSString *typeStr = @"";
//            for (FCEmployeeModel *employeeModel in employees) {
//                XMGLog(@"%@",employeeModel.Name);
//                typeStr = [NSString stringWithFormat:@"%@、%@",typeStr, employeeModel.Name];
//            }
//            if (typeStr.length > 1) {
//                typeStr = [typeStr substringFromIndex:1];
//            }
//            weakSelf.contentArr[indexPath.section][indexPath.row].value = typeStr;
//            [tableView reloadData];
//        };
        
        FCRelationTypeManagerChoiceViewController *relationTypeManagerChoiceVC = [[FCRelationTypeManagerChoiceViewController alloc] init];
        relationTypeManagerChoiceVC.idBlock = ^(FCEmployeeModel *employee) {
            weakSelf.employeeArr = [NSMutableArray arrayWithObject:employee];
            weakSelf.contentArr[indexPath.section][indexPath.row].value = employee.Name;
            [tableView reloadData];
        };
        [self.navigationController pushViewController:relationTypeManagerChoiceVC animated:YES];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}


-(void)addRelationType:(UIButton *)btn{
    [btn setEnabled:NO];
    tableObj *relationTypeName = [self getReturnCellWithCellName:RelationTypeName];
    if (relationTypeName.value.length>0) {
        if (relationTypeName.value.length>5) {
            [SVProgressHUD showErrorWithStatus:customerRelationLocaChanged(@"关系类型名称长度不能大于5",@"关系类型名称长度不能大于5")];
            [btn setEnabled:YES];
            return;
        }
        
        NSMutableDictionary *args = [NSMutableDictionary dictionary];
        if (![self.relationType.name isEqualToString:relationTypeName.value]) {
            [args setValue:relationTypeName.value forKey:@"name"];
        }
        if (self.employeeArr.count > 0) {
            [args setValue:self.employeeArr[0].Id forKey:@"managerId"];
        }
        WJCWeakSelf
        [FCCustomerRelationRequest addOrUpdateRelationTypeWithArgs:args success:^(id resultObj) {
            [btn setEnabled:YES];
            [weakSelf.navigationController popViewControllerAnimated:YES];
            [SVProgressHUD showSuccessWithStatus:customerRelationLocaChanged(@"global_general_add_success", @"添加成功")];
        } failure:^(NSError *error) {
            [btn setEnabled:YES];
            [SVProgressHUD dismiss];
        }];
    }
    else {
        [btn setEnabled:YES];
        [SVProgressHUD showErrorWithStatus:customerRelationLocaChanged(@"请输入关系类型名称",@"请输入关系类型名称")];
    }
}

#pragma mark - 编辑成功
- (void)editRelationType:(UIButton *)btn{
    [btn setEnabled:NO];
    tableObj *relationTypeName = [self getReturnCellWithCellName:RelationTypeName];
    if (relationTypeName.value.length>0) {
        if (relationTypeName.value.length>5) {
            [SVProgressHUD showErrorWithStatus:customerRelationLocaChanged(@"关系类型名称长度不能大于5",@"关系类型名称长度不能大于5")];
            [btn setEnabled:YES];
            return;
        }
        
        NSMutableDictionary *args = [NSMutableDictionary dictionary];
        if (![self.relationType.name isEqualToString:relationTypeName.value]) {
            [args setValue:relationTypeName.value forKey:@"name"];
        }
        if (self.employeeArr.count > 0) {
            [args setValue:self.employeeArr[0].Id forKey:@"managerId"];
        }
        if (self.relationType.Id.length){
            [args setObject:self.relationType.Id forKey:@"id"];
        }
        
        WJCWeakSelf
        [FCCustomerRelationRequest addOrUpdateRelationTypeWithArgs:args success:^(id resultObj) {
            [btn setEnabled:YES];
            if (weakSelf.employeeArr.count > 0) {
                if(weakSelf.idBlock){
                    weakSelf.idBlock(weakSelf.employeeArr[0]);
                }
            }
            
            [weakSelf.navigationController popViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:CrmSupplyRelationChanged object:nil];
            [SVProgressHUD showSuccessWithStatus:customerRelationLocaChanged(@"global_general_edit_success", @"编辑成功")];
        } failure:^(NSError *error) {
            [btn setEnabled:YES];
            [SVProgressHUD dismiss];
        }];
    }
    else {
        [btn setEnabled:YES];
        [SVProgressHUD showErrorWithStatus:customerRelationLocaChanged(@"请输入关系类型名称",@"请输入关系类型名称")];
    }
}

@end
